package cn.bdqn.web;

import cn.bdqn.pojo.Flower;
import cn.bdqn.service.FlowerService;
import cn.bdqn.service.impl.FlowerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/FlowerServlet")
public class FlowerServlet extends HttpServlet {

    private FlowerService fs = new FlowerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("页面请求到了servelt");

        //设置响应的编码格式、响应数据的格式、获取PrintWriter对象
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        //处理post请求的编码格式
        req.setCharacterEncoding("utf-8");
        //获取用户请求时传递的参数
        String type = req.getParameter("type");
        System.out.println("type="+type);
        /*一个servlet控制器处理多次请求*/
        if ("getAll".equals(type)) {
            //如果请求的type的值为getAll，调用业务的获取所有花卉信息
            List<Flower> list = fs.getAllFlowers();
            req.setAttribute("list", list);
            req.getRequestDispatcher("show.jsp").forward(req, resp);
        }else if("add".equals(type)){
            //如果请求的type的值为add，调用业务的新增花卉信息
            String name = req.getParameter("name");
            String anothername = req.getParameter("anothername");
            String property = req.getParameter("property");
            double price = Double.parseDouble(req.getParameter("price"));
            String production = req.getParameter("production");
            Flower f = new Flower(name,anothername,property,price,production);
            boolean b = fs.addFlower(f);
            if(b){
               out.println("<script type=\"text/javascript\">alert(\"新增成功！\");location.href=\"show.jsp\";</script>");
            }else{
                out.println("<script type=\"text/javascript\">alert(\"新增失败！\");location.href=\"show.jsp\";</script>");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);

    }
}
